package cc.magicjson.minigame.demo.ddd.application;

import cc.magicjson.minigame.demo.ddd.application.command.CreateGameCommand;
import cc.magicjson.minigame.demo.ddd.application.command.StartGameCommand;
import cc.magicjson.minigame.demo.ddd.domain.event.DomainEventPublisher;
import cc.magicjson.minigame.demo.ddd.domain.event.GameCreatedEvent;
import cc.magicjson.minigame.demo.ddd.domain.event.GameStartedEvent;
import cc.magicjson.minigame.demo.ddd.domain.model.Game;
import cc.magicjson.minigame.demo.ddd.domain.model.GameId;
import cc.magicjson.minigame.demo.ddd.domain.model.GameName;
import cc.magicjson.minigame.demo.ddd.domain.port.GameRepository;
import cc.magicjson.minigame.demo.ddd.domain.service.GameService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GameApplicationService {
    private final GameRepository gameRepository;
    private final GameService gameService;
    private final DomainEventPublisher eventPublisher;

    public GameApplicationService(GameRepository gameRepository, GameService gameService, DomainEventPublisher eventPublisher) {
        this.gameRepository = gameRepository;
        this.gameService = gameService;
        this.eventPublisher = eventPublisher;
    }

    @Transactional
    public GameId createGame(CreateGameCommand command) {
        GameId gameId = new GameId(java.util.UUID.randomUUID().toString());
        GameName gameName = new GameName(command.name());
        Game game = gameService.createGame(gameId, gameName);
        gameRepository.save(game);// 确保这里只调用一次
        return gameId;
    }

    @Transactional
    public void startGame(StartGameCommand command) {
        Game game = gameRepository.findById(command.gameId());
        gameService.startGame(game);
        gameRepository.save(game);
    }
}